"""
邮件发送API路由
"""
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session

from database import get_db
# from utils.auth import get_current_user
# from models.user import User
from schemas.email_send import (
    EmailSendRequest, EmailSendResponse, EmailTask, EmailTaskList,
    EmailSendRecord, EmailSendHistoryList, EmailStatistics,
    ContactImportRequest, ContactImportResponse,
    EmailPreviewRequest, EmailPreviewResponse
)
from models.email_task import EmailTaskStatus, EmailSendStatus
from services.email_send_service import EmailSendService

router = APIRouter(prefix="/api/emails", tags=["邮件发送"])


@router.post("/send", response_model=EmailSendResponse)
async def send_email(
    request: EmailSendRequest,
    db: Session = Depends(get_db),
    # current_user: User = Depends(get_current_user)
):
    """发送邮件"""
    try:
        return EmailSendService.create_email_task(db, request, 1)  # 暂时使用用户ID=1
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"发送邮件失败: {str(e)}")


@router.get("/tasks", response_model=EmailTaskList)
async def get_email_tasks(
    page: int = Query(1, ge=1),
    size: int = Query(10, ge=1, le=100),
    status: Optional[EmailTaskStatus] = None,
    search: Optional[str] = None,
    db: Session = Depends(get_db),
    # current_user: User = Depends(get_current_user)
):
    """获取邮件任务列表"""
    try:
        return EmailSendService.get_email_tasks(db, 1, page, size, status, search)  # 暂时使用用户ID=1
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取任务列表失败: {str(e)}")


@router.get("/tasks/{task_id}", response_model=EmailTask)
async def get_email_task(
    task_id: str,
    db: Session = Depends(get_db),
    # current_user: User = Depends(get_current_user)
):
    """获取邮件任务详情"""
    try:
        task = EmailSendService.get_email_task(db, task_id, 1)  # 暂时使用用户ID=1
        if not task:
            raise HTTPException(status_code=404, detail="任务不存在")
        return task
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取任务详情失败: {str(e)}")


@router.post("/tasks/{task_id}/cancel")
async def cancel_email_task(
    task_id: str,
    db: Session = Depends(get_db),
    # current_user: User = Depends(get_current_user)
):
    """取消邮件任务"""
    try:
        result = EmailSendService.cancel_email_task(db, task_id, 1)  # 暂时使用用户ID=1
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"取消任务失败: {str(e)}")


@router.get("/history", response_model=EmailSendHistoryList)
async def get_email_send_history(
    page: int = Query(1, ge=1),
    size: int = Query(10, ge=1, le=100),
    task_id: Optional[str] = None,
    status: Optional[EmailSendStatus] = None,
    search: Optional[str] = None,
    db: Session = Depends(get_db),
    # current_user: User = Depends(get_current_user)
):
    """获取邮件发送历史"""
    try:
        return EmailSendService.get_email_send_history(db, 1, page, size, task_id, status, search)  # 暂时使用用户ID=1
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取发送历史失败: {str(e)}")


@router.get("/statistics", response_model=EmailStatistics)
async def get_email_statistics(
    db: Session = Depends(get_db),
    # current_user: User = Depends(get_current_user)
):
    """获取邮件统计信息"""
    try:
        return EmailSendService.get_email_statistics(db, 1)  # 暂时使用用户ID=1
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取统计信息失败: {str(e)}")


@router.post("/import-contacts", response_model=ContactImportResponse)
async def import_contacts(
    request: ContactImportRequest,
    db: Session = Depends(get_db),
    # current_user: User = Depends(get_current_user)
):
    """从数据源导入联系人"""
    try:
        return EmailSendService.import_contacts(db, request, 1)  # 暂时使用用户ID=1
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"导入联系人失败: {str(e)}")


@router.post("/preview", response_model=EmailPreviewResponse)
async def preview_email_content(
    request: EmailPreviewRequest,
    db: Session = Depends(get_db),
    # current_user: User = Depends(get_current_user)
):
    """预览邮件内容"""
    try:
        return EmailSendService.preview_email_content(db, request, 1)  # 暂时使用用户ID=1
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"预览邮件失败: {str(e)}")
